package com.zx.ishopping.services.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zx.ishopping.Constants.DeleteConstant;
import com.zx.ishopping.Constants.InsertConstant;
import com.zx.ishopping.DTO.GetOrderListDTO;
import com.zx.ishopping.DTO.OrderDTO;
import com.zx.ishopping.DTO.OrderPageDTO;
import com.zx.ishopping.VO.CartItemVo;
import com.zx.ishopping.VO.OrderVo;
import com.zx.ishopping.entity.*;
import com.zx.ishopping.exceptions.OrderException;
import com.zx.ishopping.mapper.*;
import com.zx.ishopping.results.PageResult;
import com.zx.ishopping.services.OrderService;
import com.zx.ishopping.utils.OrderNumberUtils;
import com.zx.ishopping.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemsMapper orderItemsMapper;
    
    @Autowired
    private CartMapper cartMapper;
    
    
    @Autowired
    private CartItemMapper cartItemMapper;
    
    
    @Autowired
    private OrderNumberUtils orderNumberUtils;
    
    @Autowired
    private AddressMapper  addressMapper;
    
    
    /**
     * 订单分页查询
     * @param orderPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrderPageDTO orderPageQueryDTO) {
        PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());
        Page<OrderVo> page = orderMapper.pageQuery(orderPageQueryDTO);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setData(page.getResult());
        return pageResult;
    }

    /**
     * 删除订单
     * @param id 订单id
     */
    @Override
    @Transactional
    public void deleteOrder(Long id) {
        
        //1.首先根据id查询订单，判断订单是否为已完成或已取消
        Order order = orderMapper.getById(id);
        if(order.getStatus() == 3 || order.getStatus() == 4){
            //此时状态为已完成或已取消
            //删除订单需要删除订单中的内容 根据订单id删除商品
            orderItemsMapper.deleteOrderItems(id);

            orderMapper.deleteOrder(id);
        }else {
            throw new RuntimeException(DeleteConstant.ERROR_ORDER_CANNOT_BE_DELETED);
        }

    }

    /**
     * 更新修改订单
     * @param orderDTO
     */
    @Override
    public void updateOrder(OrderDTO orderDTO) {
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO,order);
        orderMapper.updateOrder(order);
    }

    /**
     * 管理员修改订单状态
     * @param status
     * @param id
     */
    @Override
    public void updateOrderStatus(Integer status,Long id) {
        
        if (status == 0){
            orderMapper.updateOrderStatusAndCreateTime(status,id);
        }
        orderMapper.updateOrderStatus(status,id);
    }

    /**
     * 获取订单状态数量
     * @return
     */
    @Override
    public List<OrderStatusCount> getOrderCountByStatus() {
        List<OrderStatusCount> orderStatusCounts = orderMapper.getOrderCountByStatus();
        return orderStatusCounts;
    }

    /**
     * 获取订单列表
     * @param getOrderListDTO
     * @return
     */
    @Override
    public List<OrderVo> getOrderList(GetOrderListDTO getOrderListDTO) {
        Long userId = ThreadLocalUtil.get();
        getOrderListDTO.setUserId(userId);
        List<OrderVo> orderList = orderMapper.getOrderList(getOrderListDTO);
        return orderList;
    }

    @Transactional
    @Override
    public void addOrder(Long addressId) {
        Order order = new Order();
        Long userId = ThreadLocalUtil.get();
        order.setUserId(userId);
        //根据userId获取购物车id
       Cart cart = cartMapper.getCartInfo(userId);
       
       //获取购物车中的商品
        List<CartItemVo>  list = cartItemMapper.getCartItems(cart.getId());
        
        if (list.isEmpty()){
            throw new OrderException(InsertConstant.CART_IS_NULL);
        }
        
        //创建订单
        //1.生成订单号
        String orderNumber = orderNumberUtils.getOrderNumber();
        //2.设置订单中的参数
        order.setOrderNumber(orderNumber);
        order.setTotalAmount(cart.getTotalPrice());
        //3.根据地址id获取地址信息
        Address addressById = addressMapper.getAddressById(addressId);
        //4.设置地址和电话，和收件人
        order.setName(addressById.getName());
        order.setPhoneNum(addressById.getName());
        String address = addressById.getProvince() + addressById.getCity() + addressById.getDistrict() + addressById.getDetail();
        order.setAddress(address);
        
        orderMapper.addOrder(order);
        //订单创建成功后，将购物车的商品添加到订单详情
        for (CartItemVo cartItem : list) {
            OrderItem orderItems = new OrderItem();
            orderItems.setOrderId(order.getId());
            orderItems.setProductId(cartItem.getProductId());
            orderItems.setTotalPrice(cartItem.getTotalPrice());
            orderItems.setQuantity(cartItem.getQuantity());
            orderItemsMapper.addOrderItems(orderItems);
        }
        
        //删除购物车中的内容
        cartItemMapper.deleteOrderItems(cart.getId());
        
        //设置购物车为空
        cart.setTotalPrice(BigDecimal.valueOf(0));
        cart.setQuantity(0);
        cartMapper.update(cart);
        
    }


}
